<!DOCTYPE html>
<html lang=en>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>闭包 | Tckapco</title>
  <meta name="description" content="一、概念红宝书：闭包是指有权访问另外一个函数作用域中的变量的函数 MDN：闭包是指那些能够访问自由变量的函数 （其中自由变量，指在函数中使用的，但既不是函数参数arguments也不是函数的局部变量的变量，其实就是另外一个函数作用域中的变量） 《你不知道的JavaScript》：当函数可以记住并访问所在的词法作用域时，就产生了闭包，即使函数是在当前词法作用域之外执行。 二、产生原因作用域链首先要明">
<meta property="og:type" content="article">
<meta property="og:title" content="闭包">
<meta property="og:url" content="https://theboat.gitee.io/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="一、概念红宝书：闭包是指有权访问另外一个函数作用域中的变量的函数 MDN：闭包是指那些能够访问自由变量的函数 （其中自由变量，指在函数中使用的，但既不是函数参数arguments也不是函数的局部变量的变量，其实就是另外一个函数作用域中的变量） 《你不知道的JavaScript》：当函数可以记住并访问所在的词法作用域时，就产生了闭包，即使函数是在当前词法作用域之外执行。 二、产生原因作用域链首先要明">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-04-21T00:32:01.000Z">
<meta property="article:modified_time" content="2021-08-01T02:16:53.487Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
  <!-- Canonical links -->
  <link rel="canonical" href="https://theboat.gitee.io/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/index.html">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/blog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 5.4.0"></head>


<body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="" target="_blank">
          <img class="img-circle img-rotate" src="/blog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">Tckapco.</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Web Developer</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> GuangDong, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="Type something..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav ">
        
        
        <li class="menu-item menu-item-home">
          <a href="/blog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">Home</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">Archives</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">Categories</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">Tags</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">About</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="/blog/null" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/blog/null" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="/blog/null" target="_blank" title="Twitter" data-toggle=tooltip data-placement=top><i class="icon icon-twitter"></i></a></li>
        
        <li><a href="/blog/null" target="_blank" title="Behance" data-toggle=tooltip data-placement=top><i class="icon icon-behance"></i></a></li>
        
        <li><a href="/blog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎交流与分享经验!</p>
            </div>
        </div>
    </div>
</div>

    
      

    
      
  <div class="widget">
    <h3 class="widget-title">Tags</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/JavaScript/" rel="tag">JavaScript</a><span class="tag-list-count">2</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget-body tagcloud">
      <a href="/blog/tags/JavaScript/" style="font-size: 13px;">JavaScript</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">Archive</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/04/">April 2021</a><span class="archive-list-count">5</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2021/04/21/%E6%89%A7%E8%A1%8C%E4%B8%8A%E4%B8%8B%E6%96%87-%E6%89%A7%E8%A1%8C%E6%A0%88/" class="title">执行上下文&amp;执行栈</a>
              </p>
              <p class="item-date">
                <time datetime="2021-04-21T06:29:07.000Z" itemprop="datePublished">2021-04-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2021/04/21/%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/" class="title">数据类型</a>
              </p>
              <p class="item-date">
                <time datetime="2021-04-21T00:32:01.000Z" itemprop="datePublished">2021-04-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2021/04/21/%E9%97%AD%E5%8C%85/" class="title">闭包</a>
              </p>
              <p class="item-date">
                <time datetime="2021-04-21T00:32:01.000Z" itemprop="datePublished">2021-04-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/" class="title">闭包</a>
              </p>
              <p class="item-date">
                <time datetime="2021-04-21T00:32:01.000Z" itemprop="datePublished">2021-04-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2021/04/20/hello-world/" class="title">Hello World</a>
              </p>
              <p class="item-date">
                <time datetime="2021-04-20T14:40:15.938Z" itemprop="datePublished">2021-04-20</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-闭包 - 副本" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      闭包
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/" class="article-date">
	  <time datetime="2021-04-21T00:32:01.000Z" itemprop="datePublished">2021-04-21</time>
	</a>
</span>
        
        

        
	<span class="article-read hidden-xs">
	    <i class="icon icon-eye-fill" aria-hidden="true"></i>
	    <span id="busuanzi_container_page_pv">
			<span id="busuanzi_value_page_pv">0</span>
		</span>
	</span>


        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/#comments" class="article-comment-link">Comments</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h1 id="一、概念"><a href="#一、概念" class="headerlink" title="一、概念"></a>一、概念</h1><p><strong>红宝书</strong>：闭包是指有权访问另外一个函数作用域中的变量的函数</p>
<p><strong>MDN</strong>：闭包是指那些能够访问自由变量的函数</p>
<p>（其中自由变量，指在函数中使用的，但既不是函数参数arguments也不是函数的局部变量的变量，其实就是另外一个函数作用域中的变量）</p>
<p><strong>《你不知道的JavaScript》</strong>：当函数可以记住并访问所在的词法作用域时，就产生了闭包，即使函数是在当前词法作用域之外执行。</p>
<h1 id="二、产生原因"><a href="#二、产生原因" class="headerlink" title="二、产生原因"></a>二、产生原因</h1><h3 id="作用域链"><a href="#作用域链" class="headerlink" title="作用域链"></a>作用域链</h3><p>首先要明白作用域链的概念，在ES5中只存在两种作用域————全局作用域和函数作用域。<strong>当访问一个变量时，解释器会首先在当前作用域查找标示符，如果没有找到，就去父作用域找，直到找到该变量的标示符或者不在父作用域中，这就是作用域链</strong>，值得注意的是，每一个子函数都会拷贝上级的作用域，形成一个作用域的链条。比如:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 1;</span><br><span class="line">function fn1() &#123;</span><br><span class="line">  var a &#x3D; 2</span><br><span class="line">  function fn2() &#123;</span><br><span class="line">    var a &#x3D; 3;</span><br><span class="line">    console.log(a);  &#x2F;&#x2F;3</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这段代码中，fn1的作用域指向有全局作用域(window)和它本身，而fn2的作用域指向全局作用域(window)、fn1和它本身。而且作用域是从最底层向上找，直到找到全局作用域window为止，如果全局还没有的话就会报错。就这么简单一件事情！</p>
<p>闭包产生的本质就是，当前环境中存在指向父级作用域的引用。还是举上面的例子:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function fn1() &#123;</span><br><span class="line">  var a &#x3D; 2</span><br><span class="line">  function fn2() &#123;</span><br><span class="line">    console.log(a);&#x2F;&#x2F;2</span><br><span class="line">  &#125;</span><br><span class="line">  return fn2;</span><br><span class="line">&#125;</span><br><span class="line">var output &#x3D; fn1();</span><br><span class="line">output();</span><br></pre></td></tr></table></figure>

<p>这里x会拿到父级作用域中的变量，输出2。因为在当前环境中，含有对fn2的引用，fn2恰恰引用了window、fn1和fn2的作用域。因此fn2可以访问到fn1的作用域的变量。</p>
<p>那是不是只有返回函数才算是产生了闭包呢？</p>
<p>回到闭包的本质，我们只需要<strong>让父级作用域的引用存在</strong>即可，因此我们还可以这么做：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">var fn3;</span><br><span class="line">function fn1() &#123;</span><br><span class="line">  var a &#x3D; 2</span><br><span class="line">  fn3 &#x3D; function() &#123;</span><br><span class="line">    console.log(a);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">fn1();</span><br><span class="line">fn3();</span><br></pre></td></tr></table></figure>

<p>让fn1执行，给fn3赋值后，等于说现在<code>fn3拥有了window、fn1和fn3本身这几个作用域的访问权限</code>，还是自底向上查找，<code>最近是在fn1</code>中找到了a,因此输出2。</p>
<p>在这里是外面的变量<code>fn3存在着父级作用域的引用</code>，因此产生了闭包，形式变了，本质没有改变。</p>
<h1 id="三、表现形式"><a href="#三、表现形式" class="headerlink" title="三、表现形式"></a>三、表现形式</h1><h3 id="1-返回一个函数"><a href="#1-返回一个函数" class="headerlink" title="1.返回一个函数"></a><strong>1.返回一个函数</strong></h3><p>上面例子</p>
<h3 id="2-作为参数传递"><a href="#2-作为参数传递" class="headerlink" title="2.作为参数传递"></a><strong>2.作为参数传递</strong></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var a &#x3D; 1;</span><br><span class="line">function foo()&#123;</span><br><span class="line">  var a &#x3D; 2;</span><br><span class="line">  function baz()&#123;</span><br><span class="line">    console.log(a);</span><br><span class="line">  &#125;</span><br><span class="line">  bar(baz);</span><br><span class="line">&#125;</span><br><span class="line">function bar(fn)&#123;</span><br><span class="line">  &#x2F;&#x2F; 这就是闭包</span><br><span class="line">  fn();</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; 输出2，而不是1</span><br><span class="line">foo();</span><br></pre></td></tr></table></figure>

<h3 id="3-回调函数"><a href="#3-回调函数" class="headerlink" title="3.回调函数"></a>3.回调函数</h3><p>在定时器、事件监听、Ajax请求、跨窗口通信、Web Workers或者任何异步中，只要使用了<strong>回调函数</strong>，实际上就是在使用闭包。</p>
<p>以下的闭包保存的仅仅是window和当前作用域。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 定时器</span><br><span class="line">setTimeout(function timeHandler()&#123;</span><br><span class="line">  console.log(&#39;111&#39;);</span><br><span class="line">&#125;，100)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 事件监听</span><br><span class="line">$(&#39;#app&#39;).click(function()&#123;</span><br><span class="line">  console.log(&#39;DOM Listener&#39;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="4-立即执行函数"><a href="#4-立即执行函数" class="headerlink" title="4.立即执行函数"></a>4.立即执行函数</h3><p>与IIFE(立即执行函数表达式)一起使用</p>
<p>先介绍立即执行函数的内容</p>
<p><strong>表示方式</strong>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">!function ()&#123;</span><br><span class="line">   console.log(&quot;立即执行函数&quot;)</span><br><span class="line">&#125;.call()</span><br><span class="line"></span><br><span class="line">(function () &#123;</span><br><span class="line">   console.log(&quot;立即执行函数&quot;)</span><br><span class="line"> &#125;)();</span><br><span class="line"></span><br><span class="line"> (function () &#123;</span><br><span class="line">    console.log(&quot;立即执行函数&quot;)</span><br><span class="line"> &#125;())</span><br></pre></td></tr></table></figure>

<p><strong>演变</strong></p>
<p>1.在函数表达式后面加括号，可以立即执行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var foo &#x3D; function () &#123;</span><br><span class="line">  console.log(&quot;立即执行函数&quot;)</span><br><span class="line">&#125;();</span><br></pre></td></tr></table></figure>

<p>2.在匿名函数后加括号，不可立即执行</p>
<p>会报错，原因是JavaScript引擎遇到function时，会默认把它当作是函数声明</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function () &#123;</span><br><span class="line">   console.log(&quot;立即执行函数&quot;)</span><br><span class="line">&#125;();</span><br></pre></td></tr></table></figure>

<p>3.在函数声明后加括号，不可立即执行</p>
<p>函数声明会被提升，只留下一对括号，报错</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function foo() &#123;</span><br><span class="line">   console.log(&quot;立即执行函数&quot;)</span><br><span class="line">&#125;()</span><br></pre></td></tr></table></figure>

<h1 id="四、应用"><a href="#四、应用" class="headerlink" title="四、应用"></a>四、应用</h1><h3 id="1-循环输出问题"><a href="#1-循环输出问题" class="headerlink" title="1.循环输出问题"></a>1.循环输出问题</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">for(var i &#x3D; 1; i &lt;&#x3D; 5; i ++)&#123;</span><br><span class="line">  setTimeout(function timer()&#123;</span><br><span class="line">    console.log(i)</span><br><span class="line">  &#125;, 0)</span><br><span class="line">&#125;   &#x2F;&#x2F; 全部输出6</span><br></pre></td></tr></table></figure>

<p><strong>原因：</strong></p>
<p>因为setTimeout为<strong>宏任务</strong>，由于JS中<strong>单线程eventLoop机制</strong>，在主线程同步任务执行完后才去执行宏任务，因此循环结束后setTimeout中的回调才依次执行，但输出i的时候当前作用域没有，往上一级再找，发现了i,此时循环已经结束，i变成了6。因此会全部输出6。</p>
<p><strong>解决方法：</strong></p>
<p>1.利用IIFE(立即执行函数表达式)当每次for循环时，把此时的i变量传递到定时器中</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">for(var i &#x3D; 1;i &lt;&#x3D; 5;i++)&#123;</span><br><span class="line">  (function(j)&#123;</span><br><span class="line">    setTimeout(function timer()&#123;</span><br><span class="line">      console.log(j)</span><br><span class="line">    &#125;, 0)</span><br><span class="line">  &#125;)(i)</span><br><span class="line">&#125;   &#x2F;&#x2F; 每次循环时创建一个匿名函数并立即执行</span><br></pre></td></tr></table></figure>

<p>2.给定时器传入第三个参数, 作为timer函数的第一个函数参数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">for(var i&#x3D;1;i&lt;&#x3D;5;i++)&#123;</span><br><span class="line">  setTimeout(function timer(j)&#123;</span><br><span class="line">    console.log(j)</span><br><span class="line">  &#125;, 0, i)</span><br><span class="line">&#125;  &#x2F;&#x2F; 第三个参数起为执行函数的其他参数</span><br></pre></td></tr></table></figure>

<p>3.使用ES6中的let</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">for(let i &#x3D; 1; i &lt;&#x3D; 5; i++)&#123;</span><br><span class="line">  setTimeout(function timer()&#123;</span><br><span class="line">    console.log(i)</span><br><span class="line">  &#125;,0)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="五、优缺点"><a href="#五、优缺点" class="headerlink" title="五、优缺点"></a>五、优缺点</h1>
      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://theboat.gitee.io/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/" title="闭包" target="_blank" rel="external">https://theboat.gitee.io/blog/2021/04/21/%E9%97%AD%E5%8C%85%20-%20%E5%89%AF%E6%9C%AC/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/blog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="" target="_blank"><span class="text-dark">Tckapco.</span><small class="ml-1x">Web Developer</small></a></h3>
        <div></div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/blog/2021/04/21/%E9%97%AD%E5%8C%85/" title="闭包"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;Newer</span></a>
    </li>
    
    
    <li class="next">
      <a href="/blog/2021/04/20/hello-world/" title="Hello World"><span>Older&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  
  <div class="bar-right">
    
  </div>
  </div>
</nav>
  


</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="/blog/null" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/blog/null" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="/blog/null" target="_blank" title="Twitter" data-toggle=tooltip data-placement=top><i class="icon icon-twitter"></i></a></li>
        
        <li><a href="/blog/null" target="_blank" title="Behance" data-toggle=tooltip data-placement=top><i class="icon icon-behance"></i></a></li>
        
        <li><a href="/blog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/blog/js/plugin.min.js"></script>


<script src="/blog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: 'Posts',
            PAGES: 'Pages',
            CATEGORIES: 'Categories',
            TAGS: 'Tags',
            UNTITLED: '(Untitled)',
        },
        ROOT_URL: '/blog/',
        CONTENT_URL: '/blog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/blog/js/insight.js"></script>






   
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





   






</body>
</html>